var mongomq = require('mongomq');

var constants = require('../constants.js');
var dao = require('./notification.dao.js');

/*
 * Mongo MQ Configuration
 */
console.log('creating mongo mq...');
var queue = new mongomq.MongoMQ({
	server: constants.queue.SERVER,
	autoStart: false
});

// set server forcely
queue.mongoConnection.server.host = constants.queue.SERVER;
console.log('mongoConnection: ' + JSON.stringify(queue.mongoConnection));

queue.start(function() {
	console.log('Queue listening started.');
	console.log('active: ' + queue.mongoConnection.active);
});

exports.push = function(event, data) {
	console.log('queue emit: ' + JSON.stringify(data));
	queue.emit(event, data);
};

exports.addListener = function(event, handler) {
	queue.on(event, function(err, data, next) {
		if (err) {
			// TODO: add xception handler
		}
		
		handler(data);		
		next();
	});
};

exports.getNotifications = function(target, handler) {
	dao.getNotifications(target, handler);
};